package gl.java.network.transport.kcp.example.rtt;

import javax.swing.*;
import java.awt.*;
import java.util.Queue;

public class RttWindow extends JFrame {
    private Queue<Integer> pingQ = new java.util.ArrayDeque<>();
    int nodeWidth = 15;
    JPanel comp = new JPanel() {

        public void paint(Graphics g) {
            super.paint(g);
            Graphics2D g2d = (Graphics2D) g;

            g2d.setColor(Color.RED);
            int x = 20;
            int y = 0;
            int height = this.getParent().getHeight() - 20;
            int offsetX = 20;
            g2d.drawString(getTitle() + " rtt", offsetX, offsetX);
            g2d.drawString("ms", offsetX, offsetX + 30);
            for (int i = 0; i < pingQ.size(); i++) {
                Integer[] temp = new Integer[pingQ.size()];
                Integer[] q = pingQ.toArray(temp);
                int x2 = x + nodeWidth;
                int y2 = q[i];
                g2d.drawString(String.valueOf(y2), x2 + offsetX, height - y2);
                g2d.drawLine(x + offsetX, height - y, x2 + offsetX, height - y2);
                x = x2;
                y = y2;
            }
        }
    };

    public RttWindow() {
        this.setTitle("Rtt");
        this.add(comp);
        this.setSize(720, 360);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    public void append(long i) {
        this.pingQ.offer((int) i);
        while (pingQ.size() > (720 / nodeWidth)-6) {
            pingQ.poll();
        }
    }

    @Override
    public void update(Graphics g) {
        super.update(g);
    }

    public void close() {
        this.setVisible(false);
    }
}
